﻿using System;
using Fiddler;
using FiddlerAmfParser.Utils;

namespace FiddlerAmfParser.AmfInspectors
{
	public class AmfRequestInspector : AmfInspectorBase, IRequestInspector2
	{
		// ReSharper disable InconsistentNaming
		public HTTPRequestHeaders headers
			// ReSharper restore InconsistentNaming
		{
			get { return null; }
			set
			{
				HeaderData = value;
				IsAmfContent = DisableContentTypeCheck || value.ExistsAndEquals("content-type", "application/x-amf");
			}
		}

		public override byte[] body
		{
			get { return BodyData; }
			set
			{
				BodyData = DecodeBodyIfRequired(value);

				AmfOutput.TreeView.BeginUpdate();
				AmfOutput.TreeView.Nodes.Clear();
				AmfOutput.TreeView.EndUpdate();

				AmfOutput.StatusBox.Clear();
				AmfOutput.StatusBox.Update();
				
				if (IsAmfContent)
				{
					try
					{
						Renderer.RenderAmfToTree(BodyData, AmfOutput);
					}
					catch (Exception ex)
					{
						AmfOutput.StatusBox.AppendText(ExceptionHelper.GetMessageForException(ex));
					}
				}
				else
				{
					AmfOutput.StatusBox.AppendText("Request does not have a content-type: application/x-amf header variable. Canceled decoding.\r\n");
				}
			}
		}
	}
}